package com.yy.wga.mp.module.third.manager;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.mp.common.utils.common.JsonUtils;
import com.yy.wga.mp.module.third.request.SmsRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SmsManager {
    /**
     * 产品名称:云通信短信API产品,开发者无需替换
     */
    static final String product = "Dysmsapi";
    /**
     * 产品域名,开发者无需替换
     */
    static final String domain = "dysmsapi.aliyuncs.com";
    /**
     * 需要替换成开发者自己的AK(在阿里云访问控制台寻找)
     */

    @Value(value = "${aliyun.sms.accessKeyId:}")
    private String accessKeyId;

    @Value(value = "${aliyun.sms.accessKeySecret:}")
    private String accessKeySecret;

    private IAcsClient acsClient;

    public void send(SmsRequest request) {
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        StringBuilder phoneSb = new StringBuilder();
        //拼接手机号码
        for (String phone : request.getPhoneList()) {
            phoneSb.append(phone);
            phoneSb.append(",");
        }
        phoneSb.deleteCharAt(phoneSb.length() - 1);
        //必填:待发送手机号
        sendSmsRequest.setPhoneNumbers(phoneSb.toString());
        //必填:短信签名-可在短信控制台中找到
        sendSmsRequest.setSignName(request.getTemplateCode().getSignName());
        //必填:短信模板-可在短信控制台中找到
        sendSmsRequest.setTemplateCode(request.getTemplateCode().getTemplateCode());
        if (StringUtils.isNotBlank(request.getParams())) {
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            Map<String, Object> param = new HashMap<>();
            param.put("code", request.getParams());
            sendSmsRequest.setTemplateParam(JsonUtils.toJSONString(param));
        }
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");

        log.info("发送短信：" + sendSmsRequest.getTemplateCode() + "," + request.getParams() + "至用户" + sendSmsRequest.getPhoneNumbers());
        try {
            SendSmsResponse sendSmsResponse = initDefaultAcsClient().getAcsResponse(sendSmsRequest);
            log.info("短信" + sendSmsRequest.getPhoneNumbers() + "发送结果：" + JSONObject.toJSONString(sendSmsResponse));
            if ("OK".equals(sendSmsResponse.getCode())) {
                return;
            }
        } catch (Exception e) {
            log.error("阿里云发送短信失败：", e);
        }
        throw new BusinessException(EResponseCode.SYSTEM_BUSY_ERROR);
    }

    /**
     * 初始化客户端 此方法不执行动态刷新重新获取最新配置
     *
     * @return com.aliyuncs.IAcsClient
     * @author ludezh
     * @date 2019/10/30 14:02
     * @version 1.0.0
     */
    private IAcsClient initDefaultAcsClient() throws ClientException {
        if (null == this.acsClient) {
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //https://help.aliyun.com/document_detail/68360.html?spm=a2c4g.11186623.6.590.3b4e5777JGjrhb#h2--sdk-vpc-4
            //现在不需要处理短信状态报告和上行短信，不进行设置。
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            this.acsClient = new DefaultAcsClient(profile);
        }
        return this.acsClient;
    }
}
